package org.hd.source.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.hd.source.dto.LoginResponse;
import org.hd.source.dto.RegRequest;
import org.hd.source.entity.User;
import org.hd.source.exception.BizException;
import org.hd.source.mapper.UserMapper;
import org.hd.source.util.JwtUtils;
import org.hd.source.util.MD5Utils;
import org.hd.source.util.RedisUtils;
import org.hd.source.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;

    public LoginResponse login(String userName, String password) {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, userName));
        if(user == null){
            throw new BizException("用户不存在！");
        }

        verifyPassword(password, user.getPassword(), user.getSalt());

        user.setLastLoginTime(new Date());
        userMapper.updateById(user);

        return genLoginResp(user);
    }

    public LoginResponse register(RegRequest regRequest) {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, regRequest.getUserName()));
        if(user != null){
            throw new BizException("用户名已存在!");
        }

        user = new User();
        user.setUid(UUIDUtils.getUuid());
        user.setSalt(UUIDUtils.getUuid());
        user.setPassword(genMD5Password(regRequest.getPassword(), user.getSalt()));
        user.setCreateTime(new Date());
        user.setStatus(1);
        user.setUserName(regRequest.getUserName());
        user.setEmail(regRequest.getEmail());
        user.setLastLoginTime(new Date());
        userMapper.insert(user);
        return genLoginResp(user);
    }

    public LoginResponse genLoginResp(User user) {
        LoginResponse resp = new LoginResponse();
        LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
        userInfo.setUserName(user.getUserName());
        userInfo.setCoin(user.getCoin());
        userInfo.setIsVip(user.getIsVip());
        userInfo.setLastLoginTime(user.getLastLoginTime());
        resp.setToken(JwtUtils.createToken(user.getUid(), user.getUserName()));
        resp.setUserInfo(userInfo);

        redisUtils.set(resp.getToken(), user);
        return resp;
    }

    private String genMD5Password(String inputPassword, String salt) {
        return MD5Utils.md5(salt + inputPassword + salt);
    }

    private void verifyPassword(String inputPassword, String md5Password, String salt) {
        if(!md5Password.equals(MD5Utils.md5(salt + inputPassword + salt))){
            throw new BizException("密码错误！");
        }
    }
}
